import qs from 'qs'
import axios from 'axios'
import { Message } from 'element-ui'
import { version, encrypt } from '@/../my-config'
import { getToken } from '@u/tool/storage'
import { aesDecrypt, aesEncrypt } from '@u/tool/aes'
import store from '@/store'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: serviceApi[process.env.NODE_ENV],
  timeout: 30000,
  headers: {
    'Authorization': getToken() || '',
    'Client-Type': 'WEB',
    'Client-Version': version,
    'Content-Type': 'application/x-www-form-urlencoded',
    'Encrypt': encrypt
  },
  transformRequest: qs.stringify
})

// axios.defaults.withCredentials = true; // 允许跨域携带cookie信息

// request 请求拦截器
service.interceptors.request.use(config => {
  // 加密
  if (encrypt) {
    config = aesEncrypt(config)
  }

  return config
})

// response 响应拦截器
service.interceptors.response.use(response => {
  // 解密
  if (encrypt) {
    response = aesDecrypt(response)
  }

  // 导出数据流格式的excel
  const headers = response.headers
  if (headers['content-type'] === 'application/msexcel;charset=UTF-8') {
    return response.data
  }

  const { returnCode, data, message } = response.data
  // console.log('%c响应拦截：', 'color:#1e90ff;font-size:20px;font-weight:bold;', data);

  if (returnCode === '001') {
    return data
  } else {
    // 接口对接成功，但是抛出内部逻辑错误
    Message({
      message: message,
      type: 'error',
      duration: 3 * 1000
    })

    // 101:其他客户端登录了; 102:token 失效
    if (['101', '102'].includes(returnCode)) {
      store.dispatch('user/resetToken').then(() => {
        router.replace(
          '/login',
          () => Message({
            type: 'info',
            message: '登录失效，请重新登陆'
          })
        )
      })
    }

    return Promise.reject(data)
  }
},
error => {
  // 接口报错
  Message({
    message: error.message || '网络错误,请稍后重试',
    type: 'error',
    duration: 3 * 1000
  })
  return Promise.reject(error)
})

export default service
